package com.example.service.impl;

import com.example.mapper.AreaMapper;
import com.example.mapper.ProductMapper;
import com.example.mapper.UserAreaMapper;
import com.example.mapper.UserMapper;
import com.example.pojo.*;
import com.example.service.UserService;
import com.example.utils.ExcelUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAreaMapper userAreaMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private AreaMapper areaMapper;


    @Value("${redis.key}")
    private String redisKey;
    @Value("${redis.key2}")
    private String redisKey2;
    private String[] surname={"王","李","张","刘","陈","杨","赵","黄","周","吴","徐","孙","胡","朱","高","林","何","郭","马","罗","上官","令狐","慕容"};
    private String[] name={"子涵","欣怡","梓涵","晨曦","紫涵","诗涵","梦琪","嘉怡","子萱","雨涵","可馨","梓萱","思涵","思彤","心怡","雨萱","可欣","雨欣","涵"
            ,"雨彤","雨轩","佳怡","梦瑶","诗琪","萱","雨馨","思琪","静怡","佳琪","一诺","子轩","浩宇","浩然","博文","宇轩","子涵","雨泽","皓轩","浩轩","俊杰"
            ,"文博","浩","峻熙","子豪","天佑","俊熙","明轩","致远","睿","宇航","泽宇","鑫","一鸣","俊宇","硕","文轩","俊豪","子墨"};

    private String[] keJu={"状元", "榜眼", "探花", "进士", "贡士", "举人", "秀才", "监生", "童生", "儒生", "解元", "会元", "学士", "硕士", "博士"};

    private List<User> allUserList;
    private int countUser;
    private int countUserArea;
    private int countProduct;

    @Override
    public String addKindergarten(String originalPath,String areaPath) { //需要让有手机号的排前面
        List<Poi> poiList = ExcelUtils.readExcel(originalPath, Poi.class);
        List<AreaLevel> areaLevelList = ExcelUtils.readExcel(areaPath, AreaLevel.class);
        if(poiList==null||areaLevelList==null){
            return "文件不存在";
        }
        String userName=null;
        String headUrl=null;
        Random random=new Random();
        List<User> userList=new ArrayList<>();
        List<UserArea> userAreaList=new ArrayList<>();
        allUserList=new ArrayList<>();
        //获得当前代理对象
        UserServiceImpl proxy= (UserServiceImpl) AopContext.currentProxy();
        List<Integer> identifyNumList=new ArrayList<>();
        countUser=0;
        countUserArea=0;
        int countNoAccount=0;
        List<Poi> allHaveTelphone=new ArrayList<>();
        List<Poi> allFixTelphone=new ArrayList<>();
        List<Poi> allNoTelphone=new ArrayList<>();
        List<Poi> haveTelphone=new ArrayList<>();
        List<Poi> fixTelphone=new ArrayList<>();
        List<Poi> noTelphone=new ArrayList<>();

        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()!=null){
                    if(poi.getUserId()==-1){
                        break;
                    }
                    continue;
                }
                User user=new User();
                userName=surname[random.nextInt(surname.length)]+name[random.nextInt(name.length)];
                //头像地址
                headUrl="https://qiniu.shuji.weyiji.com/static/image/userHead/user_head"+(random.nextInt(29)+1)+".jpg";
                user.setUserName(userName);
                user.setHeadUrl(headUrl);
                if(poi.getTelephone()!=null&&!stringRedisTemplate.opsForSet().isMember(redisKey,poi.getVillageId()+poi.getTelephone())
                        &&!stringRedisTemplate.opsForSet().isMember(redisKey2,poi.getVillageId()+poi.getTelephone())){
                    user.setMobile(poi.getTelephone());
                    user.setCreateBy(0L);
                    poi.setNumber(poi.getNumber()+1);
                    identifyNumList.add(poi.getIdentifyNum());
//                    stringRedisTemplate.opsForSet().add(redisKey,poi.getVillageId()+poi.getTelephone());
                    stringRedisTemplate.opsForSet().add(redisKey2,poi.getVillageId()+poi.getTelephone());
                    haveTelphone.add(poi);
                }else if(poi.getFixTelephone()!=null){
                    if(poi.getFixTelephone().contains(";")){
                        String[] split = poi.getFixTelephone().split(";");
                        user.setMobile(split[0].replace("-",""));
                    }else {
                        user.setMobile(poi.getFixTelephone().replace("-",""));
                    }
                    user.setCreateBy(0L);
                    fixTelphone.add(poi);
                }else {
                    for (Poi poi1 : poiList) {
                        if(poi1.getTelephone()!=null&&poi1.getNumber()<3&&!poi.getVillageId().equals(poi1.getVillageId())&&poi.getAreaId().equals(poi1.getAreaId())
                                &&!stringRedisTemplate.opsForSet().isMember(redisKey,poi.getVillageId()+poi1.getTelephone())
                                &&!stringRedisTemplate.opsForSet().isMember(redisKey2,poi.getVillageId()+poi1.getTelephone())){
                            user.setMobile(poi1.getTelephone());
                            user.setCreateBy(1L); //没手机号的
                            poi1.setNumber(poi1.getNumber()+1);
                            identifyNumList.add(poi1.getIdentifyNum());
//                            stringRedisTemplate.opsForSet().add(redisKey,poi.getVillageId()+poi1.getTelephone());
                            stringRedisTemplate.opsForSet().add(redisKey2,poi.getVillageId()+poi1.getTelephone());
                            noTelphone.add(poi);
                            break;
                        }
                    }
                    if(user.getMobile()==null){
                        countNoAccount++;
                        poi.setUserId(-3); //userId为-3代表没创建账号
                        continue;
                    }
                }
                if(poi.getFixTelephone()!=null){
                    user.setEmail(poi.getFixTelephone());
                }else {
                    user.setEmail("");
                }
                for (AreaLevel areaLevel : areaLevelList) {
                    if(poi.getVillageId().equals(areaLevel.getVillageId())){
                        user.setLocation(areaLevel.getVillage());

                        for (int i = 0; i < 2; i++) {
                            UserArea userArea=new UserArea();
                            userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                            userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                            userArea.setAreaId(Long.valueOf(areaLevel.getAreaId()));
                            userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                            userArea.setAreaType(i);
                            userArea.setDelFlag(poi.getIdentifyNum());//做标记是那个换书小组的用户地址，导入数据库需要修改为正常值
                            userArea.setCreateBy(0L);
                            userAreaList.add(userArea);
                        }
                        break;
                    }
                }
                user.setAddress("");
                user.setUserType(5); //幼儿园用户类型为5
                user.setUserStatus(0);
                user.setBookStore(-1);
                user.setBookStoreDiscount(1.00);
                user.setDelFlag(0);
                user.setUpdateBy(0L);
                user.setSex(poi.getIdentifyNum());//做标记是那个换书小组的用户，不导入数据库
                userList.add(user);
                if(userList.size()%1000==0){
                    proxy.batchSave(userList,userAreaList);
                    userList.clear();
                    userAreaList.clear();
                    identifyNumList.clear();
                    allHaveTelphone.addAll(haveTelphone);
                    allFixTelphone.addAll(fixTelphone);
                    allNoTelphone.addAll(noTelphone);
                    haveTelphone.clear();
                    fixTelphone.clear();
                    noTelphone.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchSave(userList,userAreaList);
                allHaveTelphone.addAll(haveTelphone);
                allFixTelphone.addAll(fixTelphone);
                allNoTelphone.addAll(noTelphone);
            }
        } catch (Exception e) {
            e.printStackTrace();
            for (Integer i : identifyNumList) {
                for (Poi poi : poiList) {
                    if(i.equals(poi.getIdentifyNum())){
                        poi.setNumber(poi.getNumber()-1);
                        break;
                    }
                }
            }
            List<String> removeList=new ArrayList<>();
            try {
                for (User user : userList) {
                    for (Poi poi : poiList) {
                        if(poi.getIdentifyNum().equals(user.getSex())){
                            removeList.add(poi.getVillageId()+user.getMobile());
                            break;
                        }
                    }
                }
//                stringRedisTemplate.opsForSet().remove(redisKey,removeList.toArray());
                stringRedisTemplate.opsForSet().remove(redisKey2,removeList.toArray());
            } catch (Exception ex) {
                System.out.println(removeList);
                e.printStackTrace();
            }
        }
        for (Poi poi : poiList) {
            for (User user : allUserList) {
                if(poi.getIdentifyNum().equals(user.getSex())){
                    poi.setUserId(Math.toIntExact(user.getUserId()));
                    break;
                }
            }
        }
        System.out.println("缺账号："+countNoAccount);
        ExcelUtils.writeExcel(originalPath,poiList, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-自己手机号"+".xlsx",allHaveTelphone, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-固定电话"+".xlsx",allFixTelphone, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-别人手机号"+".xlsx",allNoTelphone, Poi.class);
        return "成功（新增用户："+countUser+"条，新增用户地址："+countUserArea+"条）";
    }

    @Override
    public String addBookstore(String originalPath) { //需要让有手机号的排前面
        List<Poi> poiList = ExcelUtils.readExcel(originalPath, Poi.class);
        List<AreaLevel> areaLevelList = areaMapper.selectAllUpAreaFourLevelVillage();
        if(poiList==null||areaLevelList==null){
            return "文件不存在";
        }
        Random random=new Random();
        List<User> userList=new ArrayList<>();
        List<UserArea> userAreaList=new ArrayList<>();
        allUserList=new ArrayList<>();
        //获得当前代理对象
        UserServiceImpl proxy= (UserServiceImpl) AopContext.currentProxy();
        List<Integer> identifyNumList=new ArrayList<>();
        countUser=0;
        countUserArea=0;
        int countNoAccount=0;
        List<Poi> allHaveTelphone=new ArrayList<>();
        List<Poi> allFixTelphone=new ArrayList<>();
        List<Poi> allNoTelphone=new ArrayList<>();
        List<Poi> haveTelphone=new ArrayList<>();
        List<Poi> fixTelphone=new ArrayList<>();
        List<Poi> noTelphone=new ArrayList<>();

        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()!=null){
                    continue;
                }
                User user=new User();
                if(poi.getTelephone()!=null&&!stringRedisTemplate.opsForSet().isMember(redisKey,poi.getVillageId()+poi.getTelephone())){
                    user.setUserName(poi.getName().replace("换书小组",""));
                    if(poi.getImg()!=null){
                        user.setHeadUrl(poi.getImg());
                    }else {
                        user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/user_head_cartoon"+(random.nextInt(33)+1)+".jpg");
                    }
                    user.setMobile(poi.getTelephone());
                    user.setCreateBy(0L);
                    poi.setNumber(poi.getNumber()+1);
                    identifyNumList.add(poi.getIdentifyNum());
                    stringRedisTemplate.opsForSet().add(redisKey,poi.getVillageId()+poi.getTelephone());
                    user.setBookStore(1);
                    user.setBookStoreDiscount(1.00);
                    haveTelphone.add(poi);
                }else if(poi.getFixTelephone()!=null){
                    user.setUserName(poi.getName().replace("换书小组",""));
                    if(poi.getImg()!=null){
                        user.setHeadUrl(poi.getImg());
                    }else {
                        user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/user_head_cartoon"+(random.nextInt(33)+1)+".jpg");
                    }
                    if(poi.getFixTelephone().contains(";")){
                        String[] split = poi.getFixTelephone().split(";");
                        user.setMobile(split[0].replace("-",""));
                    }else {
                        user.setMobile(poi.getFixTelephone().replace("-",""));
                    }
                    user.setCreateBy(0L);
                    user.setBookStore(1);
                    user.setBookStoreDiscount(1.00);
                    fixTelphone.add(poi);
                }else {
                    for (Poi poi1 : poiList) {
                        if(poi1.getTelephone()!=null&&poi1.getNumber()<2&&!poi.getVillageId().equals(poi1.getVillageId())&&poi.getAreaId().equals(poi1.getAreaId())
                                &&!stringRedisTemplate.opsForSet().isMember(redisKey,poi.getVillageId()+poi1.getTelephone())){
//                            user.setUserName((random.nextInt(421)+184)+"年"+keJu[random.nextInt(keJu.length)]);
                            user.setUserName(poi.getName().replace("换书小组",""));
                            user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/user_head_cartoon"+(random.nextInt(33)+1)+".jpg");
                            user.setMobile(poi1.getTelephone());
                            user.setCreateBy(1L); //没手机号的
                            poi1.setNumber(poi1.getNumber()+1);
                            identifyNumList.add(poi1.getIdentifyNum());
                            stringRedisTemplate.opsForSet().add(redisKey,poi.getVillageId()+poi1.getTelephone());
                            user.setBookStore(1);
                            user.setBookStoreDiscount(1.00);
                            noTelphone.add(poi);
                            break;
                        }
                    }
                    if(user.getMobile()==null){
                        countNoAccount++;
                        poi.setUserId(-3); //userId为-3代表没创建账号
                        continue;
                    }
                }
                if(poi.getFixTelephone()!=null){
                    user.setEmail(poi.getFixTelephone());
                }else {
                    user.setEmail("");
                }
                for (AreaLevel areaLevel : areaLevelList) {
                    if(poi.getVillageId().equals(areaLevel.getVillageId())){
//                        user.setLocation(areaLevel.getVillage());
                        user.setLocation(poi.getAddress()!=null ? poi.getAddress() : areaLevel.getVillage());

                        for (int i = 0; i < 2; i++) {
                            UserArea userArea=new UserArea();
                            userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                            userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                            userArea.setAreaId(Long.valueOf(areaLevel.getAreaId()));
                            userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                            userArea.setAreaType(i);
                            userArea.setDelFlag(poi.getIdentifyNum());//做标记是那个换书小组的用户地址，导入数据库需要修改为正常值
                            userArea.setCreateBy(0L);
                            userAreaList.add(userArea);
                        }
                        break;
                    }
                }
                user.setAddress("");
                user.setUserType(7); //书店用户类型为7
                user.setUserStatus(0);
                user.setDelFlag(0);
                user.setUpdateBy(0L);
                user.setSex(poi.getIdentifyNum());//做标记是那个换书小组的用户，不导入数据库
                String[] split = poi.getLocation().split(",");
                user.setLongitude(Double.valueOf(split[0]));
                user.setLatitude(Double.valueOf(split[1]));
                userList.add(user);
                if(userList.size()%1000==0){
                    proxy.batchSave(userList,userAreaList);
                    userList.clear();
                    userAreaList.clear();
                    identifyNumList.clear();
                    allHaveTelphone.addAll(haveTelphone);
                    allFixTelphone.addAll(fixTelphone);
                    allNoTelphone.addAll(noTelphone);
                    haveTelphone.clear();
                    fixTelphone.clear();
                    noTelphone.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchSave(userList,userAreaList);
                allHaveTelphone.addAll(haveTelphone);
                allFixTelphone.addAll(fixTelphone);
                allNoTelphone.addAll(noTelphone);
            }
        } catch (Exception e) {
            e.printStackTrace();
            for (Integer i : identifyNumList) {
                for (Poi poi : poiList) {
                    if(i.equals(poi.getIdentifyNum())){
                        poi.setNumber(poi.getNumber()-1);
                        break;
                    }
                }
            }
            List<String> removeList=new ArrayList<>();
            try {
                for (User user : userList) {
                    for (Poi poi : poiList) {
                        if(poi.getIdentifyNum().equals(user.getSex())){
                            removeList.add(poi.getVillageId()+user.getMobile());
                            break;
                        }
                    }
                }
                stringRedisTemplate.opsForSet().remove(redisKey,removeList.toArray());
            } catch (Exception ex) {
                System.out.println(removeList);
                e.printStackTrace();
            }
        }
        for (Poi poi : poiList) {
            for (User user : allUserList) {
                if(poi.getIdentifyNum().equals(user.getSex())){
                    poi.setUserId(Math.toIntExact(user.getUserId()));
                    break;
                }
            }
        }
        System.out.println("缺账号："+countNoAccount);
        ExcelUtils.writeExcel(originalPath,poiList, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-自己手机号"+".xlsx",allHaveTelphone, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-固定电话"+".xlsx",allFixTelphone, Poi.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-别人手机号"+".xlsx",allNoTelphone, Poi.class);
        return "成功（新增用户："+countUser+"条，新增用户地址："+countUserArea+"条）";
    }

    @Override
    public String addUniversityBookstore(String originalPath, String areaPath) {
        List<Poi> poiList = ExcelUtils.readExcel(originalPath, Poi.class);
        List<AreaLevel> areaLevelList = ExcelUtils.readExcel(areaPath, AreaLevel.class);
        if(poiList==null||areaLevelList==null){
            return "文件不存在";
        }
        Random random=new Random();
        List<User> userList=new ArrayList<>();
        List<UserArea> userAreaList=new ArrayList<>();
        allUserList=new ArrayList<>();
        //获得当前代理对象
        UserServiceImpl proxy= (UserServiceImpl) AopContext.currentProxy();
        countUser=0;
        countUserArea=0;

        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()!=null){
                    continue;
                }
                if(poi.getTelephone()==null){
                    poi.setUserId(-3); //-3代表没创建账号
                    continue;
                }
                User user=new User();
                user.setUserName((random.nextInt(421)+184)+"年"+keJu[random.nextInt(keJu.length)]);
                user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/user_head_cartoon"+(random.nextInt(33)+1)+".jpg");
                user.setMobile(poi.getTelephone());
                user.setCreateBy(1L); //没手机号的
                user.setBookStore(-1);  //不开通新书权限
                user.setBookStoreDiscount(1.00);
                if(poi.getFixTelephone()!=null){
                    user.setEmail(poi.getFixTelephone());
                }else {
                    user.setEmail("");
                }
                for (AreaLevel areaLevel : areaLevelList) {
                    if(poi.getVillageId().equals(areaLevel.getVillageId())){
                        user.setLocation(areaLevel.getVillage());

                        for (int i = 0; i < 2; i++) {
                            UserArea userArea=new UserArea();
                            userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                            userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                            userArea.setAreaId(Long.valueOf(areaLevel.getUniversityId()));
                            userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                            userArea.setAreaType(i);
                            userArea.setDelFlag(poi.getIdentifyNum());//标记是哪所大学的用户地址，导入数据库需要修改为正常值
                            userArea.setCreateBy(0L);
                            userAreaList.add(userArea);
                        }
                        break;
                    }
                }
                user.setAddress("");
                user.setUserType(7); //书店用户类型为7
                user.setUserStatus(0);
                user.setDelFlag(0);
                user.setUpdateBy(0L);
                user.setSex(poi.getIdentifyNum());//标记是哪所大学的用户，不导入数据库
                userList.add(user);
                if(userList.size()%1000==0){
                    proxy.batchSave(userList,userAreaList);
                    userList.clear();
                    userAreaList.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchSave(userList,userAreaList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Poi poi : poiList) {
            if(poi.getUserId()!=null){
                continue;
            }
            for (User user : allUserList) {
                if(poi.getIdentifyNum().equals(user.getSex())){
                    poi.setUserId(Math.toIntExact(user.getUserId()));
                    break;
                }
            }
        }
        ExcelUtils.writeExcel(originalPath,poiList, Poi.class);
        return "成功（新增用户："+countUser+"条，新增用户地址："+countUserArea+"条）";
    }

    @Override
    public String updateBookstoreNoTelephone(String poiPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(poiList==null){
            return "文件不存在";
        }
        List<User> userList=new ArrayList<>();
        List<Product> productList=new ArrayList<>();
        countUser=0;
        countProduct=0;
        UserServiceImpl proxy = (UserServiceImpl) AopContext.currentProxy();
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                User user = userMapper.selectByUserId(poi.getUserId());
                user.setUserName(poi.getName().replace("换书小组",""));
                user.setBookStore(1); //开通新书权限，地图显示书店要
                userList.add(user);
                List<Product> products = productMapper.selectByUserId(poi.getUserId());
                for (Product product : products) {
                    product.setStatus(6); //下架
                    productList.add(product);
                }
                if(userList.size()%40==0){
                    proxy.batchUpdate(userList,productList);
                    userList.clear();
                    productList.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchUpdate(userList,productList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（更新用户表："+countUser+"条，更新商品表："+countProduct+"条）";
    }

    @Override
    public String addRemainBookstore(String poiPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(poiList==null){
            return "文件不存在";
        }
        Random random=new Random();
        List<User> userList=new ArrayList<>();
        List<UserArea> userAreaList=new ArrayList<>();
        UserServiceImpl proxy = (UserServiceImpl) AopContext.currentProxy();
        allUserList=new ArrayList<>();
        countUser=0;
        countUserArea=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()!=null){
                    continue;
                }
                User user=new User();
                user.setUserName(poi.getName().replace("换书小组",""));
                if(poi.getImg()!=null){
                    user.setHeadUrl(poi.getImg());
                }else {
                    user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/user_head_cartoon"+(random.nextInt(33)+1)+".jpg");
                }
                user.setMobile("");
                user.setCreateBy(1L); //没手机号的
                user.setBookStore(1);
                user.setBookStoreDiscount(1.00);
                user.setEmail("");
                user.setAddress("");
                user.setUserType(7); //书店用户类型为7
                user.setUserStatus(0);
                user.setDelFlag(0);
                user.setUpdateBy(0L);
                user.setSex(poi.getIdentifyNum());//做标记是那个换书小组的用户，不导入数据库
                AreaLevel areaLevel = areaMapper.selectAllUpAreaByVillageId(poi.getVillageId());
                user.setLocation(poi.getAddress()!=null ? poi.getAddress() : areaLevel.getVillage());
                userList.add(user);
                for (int i = 0; i < 2; i++) {
                    UserArea userArea=new UserArea();
                    userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                    userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                    userArea.setAreaId(Long.valueOf(areaLevel.getAreaId()));
                    userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                    userArea.setAreaType(i);
                    userArea.setDelFlag(poi.getIdentifyNum());//做标记是那个换书小组的用户地址，导入数据库需要修改为正常值
                    userArea.setCreateBy(0L);
                    userAreaList.add(userArea);
                }
                if(userList.size()%1000==0){
                    proxy.batchSave(userList,userAreaList);
                    userList.clear();
                    userAreaList.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchSave(userList,userAreaList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Poi poi : poiList) {
            if(poi.getUserId()!=null){
                continue;
            }
            for (User user : allUserList) {
                if(poi.getIdentifyNum().equals(user.getSex())){
                    poi.setUserId(Math.toIntExact(user.getUserId()));
                    break;
                }
            }
        }
        ExcelUtils.writeExcel(poiPath,poiList, Poi.class);
        return "成功（新增用户："+countUser+"条，新增用户地址："+countUserArea+"条）";
    }

    @Override
    public String addRecycle(String poiPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(poiList==null){
            return "文件不存在";
        }
        List<User> userList=new ArrayList<>();
        List<UserArea> userAreaList=new ArrayList<>();
        UserServiceImpl proxy = (UserServiceImpl) AopContext.currentProxy();
        allUserList=new ArrayList<>();
        countUser=0;
        countUserArea=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()!=null){
                    continue;
                }
                String[] split =null;
                if(poi.getTelephone()!=null){
                    split = poi.getTelephone().split(";");
                }else if(poi.getFixTelephone()!=null){
                    split = poi.getFixTelephone().split(";");
                }else {
                    split = new String[]{""};
                }
                String[] split1 = poi.getLocation().split(",");
                User user=new User();
                user.setUserName(poi.getName());
                if(poi.getImg()!=null){
                    user.setHeadUrl(poi.getImg());
                }else {
                    user.setHeadUrl("https://qiniu.shuji.weyiji.com/static/image/userHead/gaode/wasteRecovery_default.jpg");
                }
                user.setMobile(split[0].replace("-",""));
                user.setCreateBy(0L); //自己电话号码
                user.setBookStore(-1);  //不开通新书权限
                user.setBookStoreDiscount(null);
                if(poi.getFixTelephone()!=null){
                    user.setEmail(poi.getFixTelephone());
                }else {
                    user.setEmail("");
                }
                user.setAddress("");
                user.setUserType(1); //回收点类型为1
                user.setUserStatus(0);
                user.setLongitude(Double.valueOf(split1[0]));
                user.setLatitude(Double.valueOf(split1[1]));
                user.setDelFlag(0);
                user.setUpdateBy(0L);
                user.setSex(poi.getIdentifyNum());//做标记是那个回收点的用户，不导入数据库
                AreaLevel areaLevel = areaMapper.selectAllUpAreaByVillageId(poi.getVillageId());
                user.setLocation(poi.getAddress()!=null ? poi.getAddress() : areaLevel.getVillage());
                userList.add(user);
                for (int i = 0; i < 2; i++) {
                    UserArea userArea=new UserArea();
                    userArea.setProvinceId(Long.valueOf(areaLevel.getProvinceId()));
                    userArea.setCityId(Long.valueOf(areaLevel.getCityId()));
                    userArea.setAreaId(Long.valueOf(areaLevel.getAreaId()));
                    userArea.setVillageId(Long.valueOf(areaLevel.getVillageId()));
                    userArea.setAreaType(i);
                    userArea.setDelFlag(poi.getIdentifyNum());//做标记是那个回收点的用户地址，导入数据库需要修改为正常值
                    userArea.setCreateBy(0L);
                    userAreaList.add(userArea);
                }
                if(userList.size()%1000==0){
                    proxy.batchSave(userList,userAreaList);
                    userList.clear();
                    userAreaList.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchSave(userList,userAreaList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Poi poi : poiList) {
            if(poi.getUserId()!=null){
                continue;
            }
            for (User user : allUserList) {
                if(poi.getIdentifyNum().equals(user.getSex())){
                    poi.setUserId(Math.toIntExact(user.getUserId()));
                    break;
                }
            }
        }
        ExcelUtils.writeExcel(poiPath,poiList, Poi.class);
        return "成功（新增用户："+countUser+"条，新增用户地址："+countUserArea+"条）";
    }

    @Transactional
    public void batchUpdate(List<User> userList, List<Product> productList) {
        int u = userMapper.batchUpdate(userList);
        int p = productMapper.batchUpdate(productList);
        countUser += u;
        countProduct += p;
    }

    @Transactional
    public void batchSave(List<User> userList,List<UserArea> userAreaList) {
        int m=userMapper.batchInsert(userList);
        for (UserArea userArea : userAreaList) {
            for (User user : userList) {
                if(userArea.getDelFlag().equals(user.getSex())){
                    userArea.setUserId(user.getUserId());
                    userArea.setDelFlag(0);
                    break;
                }
            }
        }
        int n=userAreaMapper.batchInsert(userAreaList);
        allUserList.addAll(userList);
        countUser+=m;
        countUserArea+=n;
    }
}
